package com.talent.controller;

import com.talent.common.PageResult;
import com.talent.common.Result;
import com.talent.handler.BaseException;
import com.talent.mapper.ImportRecordMapper;
import com.talent.pojo.dto.SpotDTO;
import com.talent.pojo.dto.SpotServiceDTO;
import com.talent.pojo.entity.ImportRecord;
import com.talent.pojo.entity.Spot;
import com.talent.service.SpotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 点位控制器
 */
@RestController
@RequestMapping("/api/spots")
@Slf4j
public class SpotController {

    @Autowired
    private SpotService spotService;

    @Autowired
    private ImportRecordMapper importRecordMapper;

    /**
     * 分页查询点位
     */
    @GetMapping
    public Result<PageResult<Spot>> pageQuery(@RequestParam(defaultValue = "1") Integer page,
                                              @RequestParam(defaultValue = "10") Integer pageSize,
                                              String name,
                                              String address,
                                              String contactPerson,
                                              String contact,
                                              String trainingInstitution,
                                              Long categoryId) {
        log.info("分页查询点位：page={}, pageSize={}, name={}, address={}, contactPerson={}, contact={}, trainingInstitution={}, categoryId={}",
                page, pageSize, name, address, contactPerson, contact, trainingInstitution, categoryId);
        PageResult<Spot> pageResult = spotService.pageQuery(page, pageSize, name, address, contactPerson, contact, trainingInstitution, categoryId);
        return Result.success(pageResult);
    }

    /**
     * 根据ID查询点位
     */
    @GetMapping("/{id}")
    public Result<Spot> getById(@PathVariable Long id) {
        log.info("根据ID查询点位：{}", id);
        Spot spot = spotService.getById(id);
        return Result.success(spot);
    }

    /**
     * 新增点位
     */
    @PostMapping
    public Result<String> save(@Valid @RequestBody SpotDTO spotDTO) {
        log.info("新增点位：{}", spotDTO);
        spotService.save(spotDTO);
        return Result.success("新增成功");
    }

    /**
     * 更新点位
     */
    @PutMapping("/{id}")
    public Result<String> update(@PathVariable Long id, @Valid @RequestBody SpotDTO spotDTO) {
        log.info("更新点位：id={}, data={}", id, spotDTO);
        spotService.update(id, spotDTO);
        return Result.success("更新成功");
    }

    /**
     * 删除点位
     */
    @DeleteMapping
    public Result<String> deleteByIds(@RequestParam Long[] ids) {
        log.info("删除点位：{}", java.util.Arrays.toString(ids));
        spotService.deleteByIds(ids);
        return Result.success("删除成功");
    }

    /**
     * 导入点位
     */
    @PostMapping("/import")
    public Result<String> importSpots(@RequestParam("file") MultipartFile file) {
        log.info("导入点位：{}", file.getOriginalFilename());
        spotService.importSpots(file);
        return Result.success("导入成功");
    }

    /**
     * 查询导入情况
     */
    @GetMapping("/import/status")
    public Result importSpots() {
        List<ImportRecord> all = importRecordMapper.getAll();
        Map<String, Object> map = new HashMap<>();
        Boolean isCompleted = importRecordMapper.isCompeted();
        map.put("records", all);
        map.put("summary", importRecordMapper.getSummary());
        map.put("completed", isCompleted);
        return Result.success(map);
    }

    /**
     * 停止导入
     */
    @PostMapping("/import/stop")
    public Result stopImport(){
        log.info("停止点位导入");
        spotService.stopImport();
        return Result.success("停止导入成功");
    }

    /**
     * 导出点位
     */
    @GetMapping("/export")
    public void exportSpots(Long[] ids, HttpServletResponse response) {
        log.info("导出点位：ids={}", ids);
        spotService.exportSpots(ids, response);
    }

    /**
     * 为点位分配服务菜单
     */
    @PostMapping("/{spotId}/services")
    public Result<String> assignServices(@PathVariable Long spotId, @Valid @RequestBody SpotServiceDTO spotServiceDTO) {
        log.info("为点位分配服务：spotId={}, serviceIds={}", spotId, spotServiceDTO.getServiceIds());
        spotService.assignServices(spotId, spotServiceDTO.getServiceIds());
        return Result.success("分配成功");
    }

    /**
     * 下载点位导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        log.info("下载点位导入模板");
        try {
            Resource resource = new ClassPathResource("static/点位导入模板.xlsx");
            InputStream inputStream = resource.getInputStream();

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = URLEncoder.encode("点位导入模板.xlsx", StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 将文件流写入响应
            StreamUtils.copy(inputStream, response.getOutputStream());
            inputStream.close();
        } catch (IOException e) {
            log.error("下载点位导入模板失败", e);
            throw new BaseException("模板文件下载失败");
        }
    }
}
